/*
 * private-4.c
 * Back-end for 4bit data operations
 *
 *  Created on: Sep 28, 2009
 *      Author: Orlando Arias
 *	   License: GPLv3
 *
 *   libhd44780 for Arduino systems.
 *   Copyright (C) 2009  Orlando Arias
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "WProgram.h"
#include "common/common_private.h"

#include "private-4.h"

uint8_t lcd4_getRaw(LCD4 *l, uint8_t rs_state){
	// prepare return value and data fetch operation
	uint8_t retVal = 0;
	digitalWrite(l->rs_pin, rs_state);
	digitalWrite(l->rw_pin, HIGH);
	delayMicroseconds(1);			// must wait 40 ns before driving strobe high

	// set up strobe and wait for first nibble
	digitalWrite(l->strobe, HIGH);
	delayMicroseconds(1);			// must wait 160 ns before data is available

	// fetch first nibble
	for (uint8_t i = 0; i<4; i++){
		pinMode(l->datapin[i], INPUT);
		retVal <<= 1;
		retVal |= digitalRead(l->datapin[3 - i]);
		//retVal |= (digitalRead(l->datapin[i]) << (i+4));
		pinMode(l->datapin[i], OUTPUT);
	}
	// finish pulse and prepare next one
	digitalWrite(l->strobe, LOW);
	delayMicroseconds(1);			// must wait 160 ns before sending second pulse
	digitalWrite(l->strobe, HIGH);
	delayMicroseconds(1);			// must wait 160 ns before data is available

	// fetch second nibble and finish building the byte
	for (uint8_t i = 0; i<4; i++){
		pinMode(l->datapin[i], INPUT);
		retVal <<= 1;
		retVal |= digitalRead(l->datapin[3 - i]);
		// retVal |= (digitalRead(l->datapin[i]) << i);
		pinMode(l->datapin[i], OUTPUT);
	}

	// finish pulse
	digitalWrite(l->strobe, LOW);

	return retVal;
}

void lcd4_sendRaw(LCD4 *l, uint8_t data, uint8_t rs_state){
	// prepare to send data
	digitalWrite(l->rs_pin, rs_state);
	digitalWrite(l->rw_pin, LOW);

	// write most significant nibble
	lcd4_writeNibble(l, data>>4);
	// commit
	lcd_triggerStrobe(l->strobe);

	// write least significant nibble
	lcd4_writeNibble(l, data);
	// commit
	lcd_triggerStrobe(l->strobe);

}

void lcd4_writeNibble(LCD4 *l, uint8_t nibble){
	/*
	 *  Technically speaking, uint8_t is one byte long.
	 *  The upper end of the byte will be ignored
	 *  processing * * * * A B C D only.
	 */
	for (uint8_t i = 0; i< 4; i++){
		digitalWrite(l->datapin[i], nibble & 0x01);
		nibble >>= 1;
	}
	delayMicroseconds(1);		// Wait for data to settle before returning
}
